package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.UserinfoVo;
import com.example.demo.mapper.ArticleMapper;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author：徐志荣
 * @Date：2023/6/26 下午 4:33
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/reg")
    public AjaxResult reg(Userinfo userinfo){
        //非空校验 和 参数有效性校验
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername())||
                !StringUtils.hasLength(userinfo.getPassword())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //密码加盐处理
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        return AjaxResult.success(userService.reg(userinfo));
    }

    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request,String  username , String password,String yanzhengma){
        //非空校验 和 参数有效性校验
        if(!StringUtils.hasLength(username) ||
                !StringUtils.hasLength(password)||
        !StringUtils.hasLength(yanzhengma)){
            return AjaxResult.fail(-1,"非法请求");
        }
        HttpSession httpSession = request.getSession(false);

        Userinfo userinfo = userService.getUserByName(username);
        String yanzheng = (String) httpSession.getAttribute("code");
        if(yanzheng.equalsIgnoreCase(yanzhengma) && userinfo!=null && userinfo.getId()>0){
            //有效用户名
            //两个密码是否相同
            if(PasswordUtils.check(password,userinfo.getPassword())){
                //登陆成功
                // 将用户存储到 session
                //需要创建会话
                HttpSession session = request.getSession();
                session.setAttribute(AppVariable.USER_SESSION_KEY,userinfo);

                //返回前端之前,隐藏 敏感信息
                userinfo.setPassword("");
                return AjaxResult.success(userinfo);
            }
        }

        return AjaxResult.fail(0,null);
    }

    @RequestMapping("/showinfo")
    public AjaxResult showInfo(HttpServletRequest request){
        UserinfoVo userinfoVo = new UserinfoVo();
        // todo: 1. 得到当前登录用户(从session中获取)
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null){
            return AjaxResult.fail(-1,"非法请求");
        }
        //Spring提供的深克隆方法
        BeanUtils.copyProperties(userinfo,userinfoVo);
        // todo: 2.得到用户发表文章的总数
        //设置总数的字段              service 的 方法              user 的 id
        userinfoVo.setArtCount(articleService.getArtCountByUid(userinfo.getId()));

        return AjaxResult.success(userinfoVo);
    }

    //注销(退出登录)
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session){
        session.removeAttribute(AppVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    //根据用户id 查询 user对象
    @RequestMapping("/getuserbyid")
    public AjaxResult getuserbyid(Integer id){
        if(id == null || id <0){
          return   AjaxResult.fail(-1,"非法请求");
        }

        Userinfo userinfo = userService.getUserById(id);
        if(userinfo == null ||userinfo.getId()<=0 ){
          return  AjaxResult.fail(-1,"没有该数据");
        }
        //去除 userinfo中的敏感信息
        userinfo.setPassword("");

        UserinfoVo userinfoVo = new UserinfoVo();
        BeanUtils.copyProperties(userinfo,userinfoVo);

        //查询当前用户发表的文章数
        userinfoVo.setArtCount(articleService.getArtCountByUid(id));

        return AjaxResult.success(userinfoVo);
    }

    @RequestMapping("/code")
    public void getCode(HttpSession session, HttpServletResponse response) throws IOException {
        // 利用 hutool 工具，生成验证码图片资源
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(80, 40, 4, 5);

        // 获得生成的验证码字符
        String code = captcha.getCode();

        // 利用 session 来存储验证码
        session.setAttribute("code",code);

        // 将验证码图片的二进制数据写入【响应体 response 】
        captcha.write(response.getOutputStream());
    }



}
